package com.ruoyi.seckill;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.mapper.SeckillGoodsMapper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Arrays;

@Service
public class SeckillService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate; // 或KafkaTemplate
    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    // 加载Lua脚本，在应用启动时进行
    private DefaultRedisScript<Long> seckillScript;
    @PostConstruct
    public void initScript() {
        seckillScript = new DefaultRedisScript<>();
        seckillScript.setLocation(new ClassPathResource("lua/seckill.lua"));
        seckillScript.setResultType(Long.class);
    }

    /**
     * 处理抢购请求
     * @param goodsId 商品ID
     * @param userId 用户ID
     * @return 结果
     */
    public AjaxResult seckill(Long goodsId, Long userId) {
        // 执行Lua脚本
        Long result = stringRedisTemplate.execute(
                seckillScript,
                Arrays.asList(goodsId.toString(), userId.toString())
                // 这里可以传递额外参数，本例中Lua脚本未使用ARGV，故留空
        );

        if (result == null) {
            return AjaxResult.error("系统异常");
        }

        // 根据Lua脚本返回码处理
        switch (result.intValue()) {
            case 0:
                return AjaxResult.error("商品已售罄");
            case 2:
                return AjaxResult.error("您已经参与过本次抢购");
            case 1:
                // Lua脚本执行成功，发送消息到MQ进行异步下单
                SeckillMessage message = new SeckillMessage(userId, goodsId);
                rabbitTemplate.convertAndSend("seckill.exchange", "seckill.queue-key", message);
                return AjaxResult.success("抢购请求已提交，正在处理中");
            default:
                return AjaxResult.error("未知状态");
        }
    }
}
